﻿using Apex.ASPNETCore;
using Apex.ASPNETCore.GlobalException;
using Apex.Commons.Extentions;
using Apex.EventBus.EventBuses;
using Microsoft.AspNetCore.Mvc;
using TestService.WebAPI.Controllers;
using WebApiTest.Events;

namespace WebApiTest.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IEventBus eventBus;
        private readonly ILogger<UserController> logger;
        private readonly IDistributedCacheHelper distCache;
        private readonly IMemoryCacheHelper memoryCache;

        public UserController(IEventBus eventBus, ILogger<UserController> logger, IDistributedCacheHelper distCache, IMemoryCacheHelper memoryCache)
        {
            this.eventBus = eventBus;
            this.logger = logger;
            this.distCache = distCache;
            this.memoryCache = memoryCache;
        }

        /// <summary>
        /// 通过创建用户测试：事件触发、日志保存
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> CreatedUserForTestEvent(string name)
        {
            //生成的密码短信发给对方
            var eventData = new UserCreatedEvent(name,18);
            eventBus.Publish("UserCreated", eventData);
            logger.LogInterpolatedInformation($"创建用户：{name}");
            return Ok();
        }

        /// <summary>
        /// 通过查询用户测试：内存缓存
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<int?> GetUserAgeForTestMemoryCache(string name)
        {
            var cacheKey = $"name_{name}";
            int? cachedValue = await memoryCache.GetOrCreateAsync(cacheKey, async (e) =>
            {
                e.SlidingExpiration = TimeSpan.FromSeconds(5);
                // 休眠1秒钟
                Thread.Sleep(1000);
                var age = 20;
                return age;
            }, 60);
            return cachedValue;
        }

        /// <summary>
        /// 通过查询用户测试：分布式缓存
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<int?> GetUserAgeForTestDisCache(string name)
        {
            var cacheKey = $"name_{name}";
            int? cachedValue = await distCache.GetOrCreateAsync(cacheKey, async (e) =>
            {
                e.SlidingExpiration = TimeSpan.FromSeconds(5);
                // 休眠1秒钟
                Thread.Sleep(1000);
                var age = 18;
                return age;
            }, 60);
            return cachedValue;
        }

        /// <summary>
        /// 通过查询用户测试：自定义API报错
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetUserForTestAPIError(Req req)
        {
            if (req.name == "1")
            {
                return BadRequest("test");
            }
            string newName = req.name.Substring(0, 2);  
            var res = new GlobalResponseResult<Req>()
            {
                StatusCode = 200,
                Message = "1",
                Data = req
            };
            return Ok(res);
        }

        /// <summary>
        /// 通过查询用户测试：自定义API报错
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetUserForTestAPIError(string name,int age)
        {
            if (name == "1")
            {
                return BadRequest("text");
            }
            string newName = name.Substring(0, 5);
            return Ok("1");
        }
    }
}
